//
//  CNEmoKeyboardView.swift
//  EmoticonKeyboard
//
//  Created by 陈锦聪 on 16/4/1.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

private let reuseIdentifier = "CNEmoKeyboardCell"

class CNEmoKeyboardView: UIView {
    // MARK: - 属性
    weak var textView: UITextView?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 216)
        super.init(frame: newFrame)
        prepareUI()
    }
    private func prepareUI() {
        addSubview(collectionView)
        addSubview(toolBar)
        addSubview(pageControl)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[CV]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["CV" : collectionView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[TB]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["TB" : toolBar]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[CV]-0-[TB(37)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["CV" : collectionView, "TB" : toolBar]))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 25))
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = collectionView.bounds.size
    }
    // MARK: - LazyLoad
    private lazy var pageControl: UIPageControl = {
        let control = UIPageControl()
        control.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        control.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        return control
    }()
    private lazy var toolBar: CNToolBar = {
        let view = CNToolBar.toolBar()
        view.delegate = self
        return view
    }()
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumLineSpacing = 0
        let view = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        view.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        view.pagingEnabled = true
        view.showsHorizontalScrollIndicator = false
        view.bounces = false
        view.dataSource = self
        view.delegate = self
        view.registerClass(CNEmoKeyboardCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        return view
    }()
}
// MARK: - CNToolBarDelegate
extension CNEmoKeyboardView: CNToolBarDelegate {
    func toolBar(toolBar: CNToolBar, didSelectType type: CNToolBarButtonType) {
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        setupPageControl(indexPath)
    }
}
// MARK: - CNEmoKeyboardCellDelegate
extension CNEmoKeyboardView: CNEmoKeyboardCellDelegate {
    func didSelectEmoticon(emoticon: CNEmoticonModel) {
//        print("\(emoticon.chs)")
        textView?.insertEmoticon(emoticon)
        CNEmoticonManager.sharedInstance.addFavorite(emoticon)
    }
    func deleteOneEmoticon() {
        textView?.deleteBackward()
    }
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension CNEmoKeyboardView: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CNEmoticonManager.sharedInstance.packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CNEmoticonManager.sharedInstance.packages[section].pageEmos.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CNEmoKeyboardCell
        cell.indexPath = indexPath
        cell.pageEmos = CNEmoticonManager.sharedInstance.packages[indexPath.section].pageEmos[indexPath.item]
        cell.delegate = self
        return cell
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        var refCenter = collectionView.center
        refCenter.x += collectionView.contentOffset.x
        // 可见cell
        for cell in collectionView.visibleCells() {
            if cell.frame.contains(refCenter) {
                let indexPath = collectionView.indexPathForCell(cell)
                toolBar.scrollToSection(indexPath!.section)
                setupPageControl(indexPath!)
                break
            }
        }
    }
    private func setupPageControl(indexPath: NSIndexPath) {
        pageControl.numberOfPages = CNEmoticonManager.sharedInstance.packages[indexPath.section].pageEmos.count
        pageControl.currentPage = indexPath.item
        pageControl.hidden = indexPath.section == 0
    }
}